/**
 * @BelongsProject: Baidu_Translation_API
 * @Author: 小蓝
 * @My Gitee URL: https://gitee.com/Shadows1946397262
 * @CreatingTime: 2023--24 18:30
 * @Description: A project with Baidu Translation API
 * @Version: 1.0
 */

//导入加密框架
import cryptoFramework from '@ohos.security.cryptoFramework';

//导入http模块
import http from '@ohos.net.http';


/*
 * 函数名: Generate_number_Sequence_10
 * 描述: 随机生成携带十个元素的数字序列（此序列的数据类型为字符串）
 */
function Generate_number_Sequence_10():string{

  var ret:string = ''

  for(var i = 0; i < 10; ++i){
    ret += Math.floor(Math.random()*9.999)
  }

  console.info('------[Random] '+ret)
  return ret

}

/*
 * 函数名: Transform_10_To_16
 * 描述: 用于将10进制整数序列（参数的数据类型为Uint8Array）转换为16进制整数序列（输出的数据类型为字符串）的辅助函数
 */
function Transform_10_To_16(Sign_10:Uint8Array):string{
  let Array_16 = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
  let Sign_16:string = ''
  for(var item of Sign_10) Sign_16 += Array_16[(item-item%16)/16]+Array_16[item%16]
  console.info('------[MD5 16]: '+Sign_16.toString())
  return Sign_16
}

/*
 * 函数名: Generate_Sign
 * 描述: 通过MD5模块进行信息加密, 以生成签名
 */
async function Generate_Sign(query:string,appId:string, key:string, sequence_10:string){

  //预定义输出
  let output = {
    'ifComplete':false,
    'Sign_16':null,
  }

  //创建md模块
  let MD5 = cryptoFramework.createMd('MD5')

  //MD5加密的输入值
  let sign = appId + query + sequence_10 + key

  //数据转换
  var arr = []
  for(var i = 0 ; i < sign.length ; i++)arr.push(sign.charCodeAt(i))
  var dataBlog = {
    data:new Uint8Array(arr)
  }
  console.info('------[MD5 10] dataBlog: '+dataBlog.data.toString())

  //开始MD5加密
  await MD5.update(dataBlog)
  var SecretSign
  await MD5.digest().then((mdOutput) => {
    SecretSign = mdOutput.data
    console.info("------[MD5 10] MD result: " + SecretSign.toString());
    output.ifComplete = true
    output.Sign_16 = SecretSign
  }).catch((err) => console.error("------[MD5 10] err: " + err.code))

  output.Sign_16 = Transform_10_To_16(SecretSign)

  //输出加密结果
  return output

}

/*
 * 枚举名: TranslationForm
 * 描述: 用于确定翻译流程的始末
 */
export enum TranslationForm{

  From_En_To_Zh = 0,

  From_Zh_To_En = 1

}

/*
 * 数据类型名: TranslationResult
 * 描述: 类XL_Translation_Tool的translate方法返回的数据类型
 */
declare type TranslationResult = {

  ifComplete:boolean

  result:string

  description:string

}

class XL_Translation_Tool{

  private TAG:string = '------[XL_Translation_Tool] '

  private Baidu_Translation_API_URL_Prefix:string = 'https://fanyi-api.baidu.com/api/trans/vip/translate'

  private Baidu_APPID:string = ''

  private Baidu_Key:string = ''

  private If_Provide_Developer_Info:boolean = false

  /*
   * 方法名: provideDeveloperInfo
   * 描述: 为XL_Translation_Tool提供百度翻译平台的开发者信息, 这是百度翻译API得以被调用的前提
   */
  public provideDeveloperInfo(appId:string, key:string){
    this.Baidu_APPID = appId
    this.Baidu_Key = key
    this.If_Provide_Developer_Info = true
  }

  /*
   * 方法名: translate
   * 描述: 将输入的字符串信息, 通过百调用度翻译API进行翻译并返回
   */
  public async translate(message:string, form:TranslationForm):Promise<TranslationResult>{

    //预定义返回值
    var ret:TranslationResult = {
      ifComplete:false,
      result:null,
      description:''
    }

    //判断appId和key是否被提供
    if(!this.If_Provide_Developer_Info){
      ret.description = '请为翻译工具提供百度智能翻译平台的开发者信息'
      console.info(this.TAG+'Please provide the appId and key')
      return ret
    }

    //通过http模块实例化HttpRequest
    var httpRequest = http.createHttp()

    let from:string
    let to:string
    let query:string = message+''

    if(form == TranslationForm.From_En_To_Zh){
      from = 'en'
      to = 'zh'
    }else if(form == TranslationForm.From_Zh_To_En){
      from = 'zh'
      to = 'en'
    }

    //生成10位随机整数序列
    const RANDOM_SEQUENCE:string = Generate_number_Sequence_10()

    var sign:string

    //生成签名
    let msg = await Generate_Sign(query,this.Baidu_APPID,this.Baidu_Key,RANDOM_SEQUENCE)
    if(msg.ifComplete){
      sign = msg.Sign_16
    }else {
      ret.description = '加密过程出错, 请检查相关项'
      return ret
    }

    //拼接URL
    let url = this.Baidu_Translation_API_URL_Prefix
    +'?q=' + encodeURI(query)
    +'&from=' +from
    +'&to='+to
    +'&appid='+this.Baidu_APPID
    +'&salt='+RANDOM_SEQUENCE
    +'&sign='+sign

    console.info(this.TAG+'url: '+url)

    //调用request方法
    await httpRequest.request(url,{
      method:http.RequestMethod.POST,
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }).then((data)=>{
      console.info(this.TAG+'Succeed in connecting to Internet')
      // @ts-ignore
      let trans_result = JSON.parse(data.result).trans_result
      console.info(this.TAG+'Result:' + data.result);
      console.info(this.TAG+'code:' + JSON.stringify(data.responseCode));
      console.info(this.TAG+'Translate output:'+trans_result[0].dst)
      ret.ifComplete = true
      ret.description = '翻译成功'
      ret.result = trans_result[0].dst
    }).catch(err => console.error(this.TAG+'err:'+JSON.stringify(err)))

    //销毁HttpRequest实例
    httpRequest.destroy()

    //返回翻译结果
    return ret

  }

}

//导出本模块
export default new XL_Translation_Tool()